package com.zhuchang.self_rpc.test.democoding.nettydubbo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author RenPu
 * @Date 2022/2/12 14:42
 * @Version 1.0
 * @Description:
 **/
public class NettyDubboServer {

    public static void starterServer(String host,int port){
        initStarter(host,port);
    }

    public static void initStarter(String host,int port){
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup =new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        try {
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringEncoder())  //编码
                                    .addLast(new StringDecoder())  //解码
                                    .addLast(new NettyDubboHandler()); //自定义业务处理逻辑
                        }
                    });
            //绑定端口，并启动
            ChannelFuture future = serverBootstrap.bind(host,port).sync();
            System.out.println("服务提供方开始提供服务~~");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }




}
